import { useDispatch, useSelector } from "react-redux"
import type { ROOTSTATE } from "../store"
import { Descriptions, Flex, type DescriptionsProps } from "antd"
import {Title} from "../components/Title"
import { useState } from "react"
import { login } from "../store/userStore"
import { Edit } from "../components/Edit"
import { reqUpdateUser } from "../api/userApi"

export const Home = () => {
    const user = useSelector((state: ROOTSTATE) => state.userStore.user)
    const dispatch = useDispatch()
    const [status,setStatus] =useState("")
    const updateFn = async (obj:object)=>{
        const {data:newUser} = await reqUpdateUser(user.username,obj)
        dispatch(login(newUser))
        setStatus("")
    }
    const items: DescriptionsProps["items"] = [
        { 
            key:"1",
            label:"用户名",
            children:user.username
        },
        {
            key:"2",
            label:"昵称",
            children:(
                <Edit
                label="nickname"
                content={user.nickname}
                status={status === "nickname"}
                EditFn={()=>setStatus("nickname")}
                CloseFn={() => setStatus("")}
                updateFn={updateFn}
                >
                </Edit>
            )
        },
        {
            key:"3",
            label:"头像",
            children:(
            <Edit 
            label="avatar"
            content={user.avatar}
            status={status === "avatar"}
            type="img"
            EditFn={()=>setStatus("avatar")}
            CloseFn={()=>setStatus("")}
            updateFn={updateFn}
            ></Edit>
            )
        }
    ]
    return (
        <Flex vertical gap={30}>
            <Title title="个人信息"></Title>
            <Descriptions items={items} layout="vertical"></Descriptions>
        </Flex>
    )
}